package cn.pkg.config;

import com.sun.org.apache.xpath.internal.operations.String;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration()
                .master("mymaster")
                .sentinel("127.0.0.1", 16379)
                .sentinel("127.0.0.1", 16479)
                .sentinel("127.0.0.1", 16579);
        return new LettuceConnectionFactory(sentinelConfig);
    }
    @Bean
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){

        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
//        连接redis
        redisTemplate.setConnectionFactory(redisConnectionFactory);
//        指定序列化
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =new Jackson2JsonRedisSerializer(Object.class);
//        redisTemplate.setDefaultSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;


    }

    @Bean
    public Redisson redisson() {
        Config config = new Config();

        // 配置主从架构
        config.useMasterSlaveServers()
                .setMasterAddress("redis://127.0.0.1:6379") // 主节点地址
                .addSlaveAddress("redis://127.0.0.1:6380")  // 从节点地址
                .addSlaveAddress("redis://127.0.0.1:6381") // 其他从节点地址
                .addSlaveAddress("redis://127.0.0.1:6382"); // 其他从节点地址

        return (Redisson)Redisson.create(config);
    }
}
